<template>
  <NavBar safe-area-inset-top title="登录" />

  <Layout @resize="heightChaged">
    <Form @submit="logIn" :style="{ 'margin-top': marginTop + 'px' }">
      <CellGroup class="logo">
        <Image width="48" height="48" src="/favicon.ico" />
      </CellGroup>
      <CellGroup>
        <field label="用户名" v-model="account" clearable placeholder="请输入用户名" />
        <field label="密码" v-model="password" clearable type="password" placeholder="请输入密码" />
      </CellGroup>
      <div style="margin-top: 10px">
        <Button round block icon="manager-o" type="primary" @click.prevent="logIn()" native-type="submit">登录</Button>
      </div>
    </Form>
  </Layout>
</template>
<script setup>
  import md5 from 'js-md5';
  import { useStore } from 'vuex';
  import { useRoute, useRouter } from 'vue-router';

  import { ref, inject, onMounted } from 'vue';
  import { NavBar, Form, CellGroup, Field, Button, Image, Toast } from 'vant';

  import Layout from '@/components/layout/Layout.vue';

  const $store = useStore();
  const $route = useRoute();
  const $router = useRouter();
  const $http = inject('$http');

  const marginTop = ref(0);
  const account = ref('');
  const password = ref('');

  function logIn() {
    if (!account.value) {
      $message.warn({ content: '请输入账号！', key: 'valid-error', duration: 3 });

      return;
    }

    if (!password.value) {
      $message.warn({ content: '请输入密码！', key: 'valid-error', duration: 3 });

      return;
    }

    let loginData = { account: account.value, password: md5(password.value) };

    $http.post('/api/account/login', loginData, { hideTip: true }).then(rs => {
      if (rs.success) {
        $store.commit('fillConfigs', {
          userId: rs.data.Id,
          userAccount: rs.data.Account,
          userName: rs.data.UserName
        });

        localStorage.setItem('lastLoginAccount', JSON.stringify(loginData));

        $router.push('/');
      } else {
        $message.warn({ content: rs.message, key: 'valid-error', duration: 3 });
      }
    });
  }

  function heightChaged(height) {
    marginTop.value = (height - document.getElementsByClassName('content-body')[0].clientHeight) / 3;
  }

  onMounted(() => {
    let loginData = JSON.parse(localStorage.getItem('lastLoginAccount') || '{}');

    if (loginData.account && loginData.password) {
      $http.post('/api/account/login', loginData, { hideTip: true }).then(rs => {
        if (rs.success) {
          $store.commit('fillConfigs', {
            userId: rs.data.Id,
            userAccount: rs.data.Account,
            userName: rs.data.UserName
          });

          localStorage.setItem('lastLoginAccount', JSON.stringify(loginData));

          $router.push('/');
        } else {
          localStorage.removeItem('lastLoginAccount');
        }
      });
    }
  });
</script>
<style scoped>
  .logo {
    text-align: right;
    padding: 30px 10px 10px 0;
  }
</style>
